import axios, { Axios } from "axios"

export interface IRequestConfig {
  data?: any
  params?: any
  headers?: any
}

class HttpRequest {
  baseUrl!: string

  constructor(baseUrl: string) {
    this.baseUrl = baseUrl
  }

  get(url: string, config: IRequestConfig = { params: {}, headers: {} }) {
    let { params, headers } = config
    return new Promise((reslove, reject) => {
      axios.get(this.baseUrl + url, { params, headers }).then((res) => {
        if (res.status >= 200 && res.status < 300) {
          reslove(res.data)
        } else {
          reslove(res)
        }
      }).catch(err => {
        reject(err)
      })
    })
  }

  post(url: string, config: IRequestConfig = { data: {}, headers: {}, params: {} }) {
    let { data, headers, params } = config
    return new Promise((reslove, reject) => {
      axios.post(this.baseUrl + url, { ...data }, { headers, params }).then((res) => {
        if (res.status >= 200 && res.status < 300) {
          reslove(res.data)
        } else {
          reslove(res)
        }
      }).catch(err => {
        reject(err)
      })
    })
  }

  put(url: string, config: IRequestConfig = { data: {}, headers: {}, params: {} }) {
    let { data, headers, params } = config
    return new Promise((reslove, reject) => {
      axios.put(this.baseUrl + url, { ...data }, { params, headers }).then((res) => {
        if (res.status >= 200 && res.status < 300) {
          reslove(res.data)
        } else {
          reslove(res)
        }
      }).catch(err => {
        reject(err)
      })
    })
  }

  delete(url: string, config: IRequestConfig = { data: {}, params: {}, headers: {} }) {
    let { data, headers, params } = config
    return new Promise((reslove, reject) => {
      axios.delete(this.baseUrl + url, { params, headers, data }).then((res) => {
        if (res.status >= 200 && res.status < 300) {
          reslove(res.data)
        } else {
          reslove(res)
        }
      }).catch(err => {
        reject(err)
      })
    })
  }


  interceptorsReq = axios.interceptors.request
  interceptorsRes = axios.interceptors.response
 
}

export default HttpRequest